<!DOCTYPE html>
<html prefix="og: http://ogp.me/ns#">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>使用js获取位置 &middot; pfan</title>
        <meta name="description" content="首先，我们使用caniuse-cmd查看下geolocation的兼容性,几乎所有的现代浏览器都支持geolocation
Geolocation 通过使用GPS、WIFI、IP地址检测自己的位置信息，开发人员可使用这些信息给用户提供更好的搜索建议，比如附近的便利店，并实现互动。
本地资源（location sources） JavaScript提供了一个简单，但功能强大的工具来定位设备的地理定位API的形式。它包括一个小的一组易于使用的方法，可以获得设备的位置：
GPS-主要在移动设备，精确到10米 WIFI-几乎所有的联网设备 IP-仅限于区域，备选方案 采用哪种方案取决于浏览器支持，一般情况下WIFI快于GPS快于IP
使用geolocation api 通过使用caniuse-cmd，我们知道大部分浏览器支持geolocation，但我们需要做好判断，请确保可以正常使用geolocation
if (navigator.geolocation) { // 支持geolocation } else { // 不支持geolocation } navigator.geolocation有如下几个方法：
 Geolocation.getCurrentPosition() //获取当前位置 Geolocation.watchPosition() //监测定位 Geolocation.clearWatch() //清除监测  getCurrentPosition() and watchPosition() methods 的工作方式是基本相同的。这两方法目的基本相同，都是用来去获取device的位置信息吧， 都是以一个异步的工作形式来获取位置信息的， 他们也都依赖于一个attempt call的结果
navigator.geolocation.getCurrentPosition( // 位置获取成功  function(position) { position = { coords: { latitude - //纬度.  longitude - //经度.  altitude - //高度.  accuracy - //精确度.  altitudeAccuracy - //高度的准确性.">
        <meta name="HandheldFriendly" content="True">
        <meta name="MobileOptimized" content="320">
        <meta name="generator" content="Hugo 0.73.0" />
        <meta name="robots" content="index,follow">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta property="og:title" content="使用js获取位置">
<meta property="og:description" content="首先，我们使用caniuse-cmd查看下geolocation的兼容性,几乎所有的现代浏览器都支持geolocation
Geolocation 通过使用GPS、WIFI、IP地址检测自己的位置信息，开发人员可使用这些信息给用户提供更好的搜索建议，比如附近的便利店，并实现互动。
本地资源（location sources） JavaScript提供了一个简单，但功能强大的工具来定位设备的地理定位API的形式。它包括一个小的一组易于使用的方法，可以获得设备的位置：
GPS-主要在移动设备，精确到10米 WIFI-几乎所有的联网设备 IP-仅限于区域，备选方案 采用哪种方案取决于浏览器支持，一般情况下WIFI快于GPS快于IP
使用geolocation api 通过使用caniuse-cmd，我们知道大部分浏览器支持geolocation，但我们需要做好判断，请确保可以正常使用geolocation
if (navigator.geolocation) { // 支持geolocation } else { // 不支持geolocation } navigator.geolocation有如下几个方法：
 Geolocation.getCurrentPosition() //获取当前位置 Geolocation.watchPosition() //监测定位 Geolocation.clearWatch() //清除监测  getCurrentPosition() and watchPosition() methods 的工作方式是基本相同的。这两方法目的基本相同，都是用来去获取device的位置信息吧， 都是以一个异步的工作形式来获取位置信息的， 他们也都依赖于一个attempt call的结果
navigator.geolocation.getCurrentPosition( // 位置获取成功  function(position) { position = { coords: { latitude - //纬度.  longitude - //经度.  altitude - //高度.  accuracy - //精确度.  altitudeAccuracy - //高度的准确性.">
<meta property="og:type" content="article">
<meta property="og:url" content="https://blog.steps.info/2020/01/19/%E4%BD%BF%E7%94%A8js%E8%8E%B7%E5%8F%96%E4%BD%8D%E7%BD%AE/">
        <link rel="stylesheet" href="https://blog.steps.info/dist/site.css">
        <link rel="stylesheet" href="https://blog.steps.info/dist/syntax.css">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,400,600,700,300&subset=latin,cyrillic-ext,latin-ext,cyrillic">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
        
        
        
        
    </head>
    <body>
        
<script type="application/javascript">
var dnt = (navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack);
var doNotTrack = (dnt == "1" || dnt == "yes");
if (!doNotTrack) {
	(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
	(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
	m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
	})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
	ga('create', 'XXX', 'auto');
	ga('set', 'anonymizeIp', true);
	ga('send', 'pageview');
}
</script>


        <div id="wrapper">
            <header class="site-header">
                <div class="container">
                    <div class="site-title-wrapper">
                        
                            <h1 class="site-title">
                                <a title="Homepage" href="https://blog.steps.info/">Homepage</a>
                            </h1>
                        
                        <a class="button-square" href="https://blog.steps.info/index.xml"><i class="fa fa-rss"></i></a>
                        
                            <a class="button-square button-social hint--top" data-hint="Twitter" title="Twitter" href="https://twitter.com/pangel3" rel="me">
                                <i class="fa fa-twitter"></i>
                            </a>
                        
                        
                        
                            <a class="button-square button-social hint--top" data-hint="Gitlab" title="Gitlab" href="https://gitlab.com/funnypan" rel="me">
                                <i class="fa fa-gitlab"></i>
                            </a>
                        
                        
                            <a class="button-square button-social hint--top" data-hint="Github" title="Github" href="https://github.com/RazzilDarkbrew" rel="me">
                                <i class="fa fa-github-alt"></i>
                            </a>
                        
                        
                            <a class="button-square button-social hint--top" data-hint="Stack Overflow" title="Stack Overflow" href="https://stackoverflow.com/users/7784704/stepsinfo" rel="me">
                                <i class="fa fa-stack-overflow"></i>
                            </a>
                        
                        
                        
                            <a class="button-square button-social hint--top" data-hint="Email" title="Email" href="mailto:gemini0525@foxmail.com">
                                <i class="fa fa-envelope"></i>
                            </a>
                        
                    </div>

                    <ul class="site-nav">
                        
                    </ul>
                </div>
            </header>

            <div id="container">


<div class="container">
    <article class="post-container" itemscope="" itemtype="http://schema.org/BlogPosting">
        <header class="post-header">
    <h1 class="post-title" itemprop="name headline">使用js获取位置</h1>
    
    <p class="post-date">
        <span>Published <time datetime="2020-01-19" itemprop="datePublished">Sun, Jan 19, 2020</time></span>
        <span>by</span>
        <span itemscope="" itemprop="author" itemtype="https://schema.org/Person">
            <span itemprop="name">
                <a href="https://github.com/RazzilDarkbrew" itemprop="url" rel="author">pfan</a>
            </span>
        </span>
    </p>
    
        <p class="post-reading post-line">
            <span>Estimated reading time: 1 min</span>
        </p>
    
</header>

        <div class="post-content clearfix" itemprop="articleBody">
    

    <p><img src="https://cdn.jsdelivr.net/gh/funnypan/pics@master/images/20190121163457.png" alt="quick-tip-detecting-your-location-with-javascript"></p>
<p>首先，我们使用caniuse-cmd查看下geolocation的兼容性,几乎所有的现代浏览器都支持geolocation</p>
<p>Geolocation
通过使用GPS、WIFI、IP地址检测自己的位置信息，开发人员可使用这些信息给用户提供更好的搜索建议，比如附近的便利店，并实现互动。</p>
<p>本地资源（location sources）
JavaScript提供了一个简单，但功能强大的工具来定位设备的地理定位API的形式。它包括一个小的一组易于使用的方法，可以获得设备的位置：</p>
<p>GPS-主要在移动设备，精确到10米
WIFI-几乎所有的联网设备
IP-仅限于区域，备选方案
采用哪种方案取决于浏览器支持，一般情况下WIFI快于GPS快于IP</p>
<p>使用geolocation api
通过使用caniuse-cmd，我们知道大部分浏览器支持geolocation，但我们需要做好判断，请确保可以正常使用geolocation</p>
<div class="highlight"><pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="k">if</span> <span class="p">(</span><span class="nx">navigator</span><span class="p">.</span><span class="nx">geolocation</span><span class="p">)</span> <span class="p">{</span>
  <span class="c1">// 支持geolocation
</span><span class="c1"></span><span class="p">}</span> 
<span class="k">else</span> <span class="p">{</span>
  <span class="c1">// 不支持geolocation
</span><span class="c1"></span><span class="p">}</span>
</code></pre></div><p>navigator.geolocation有如下几个方法：</p>
<ul>
<li>Geolocation.getCurrentPosition() //获取当前位置</li>
<li>Geolocation.watchPosition() //监测定位</li>
<li>Geolocation.clearWatch() //清除监测</li>
</ul>
<p>getCurrentPosition() and watchPosition() methods 的工作方式是基本相同的。这两方法目的基本相同，都是用来去获取device的位置信息吧， 都是以一个异步的工作形式来获取位置信息的， 他们也都依赖于一个attempt call的结果</p>
<div class="highlight"><pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="nx">navigator</span><span class="p">.</span><span class="nx">geolocation</span><span class="p">.</span><span class="nx">getCurrentPosition</span><span class="p">(</span>

    <span class="c1">// 位置获取成功
</span><span class="c1"></span>    <span class="kd">function</span><span class="p">(</span><span class="nx">position</span><span class="p">)</span> <span class="p">{</span>

        <span class="nx">position</span> <span class="o">=</span> <span class="p">{</span>
            <span class="nx">coords</span><span class="o">:</span> <span class="p">{</span>
                <span class="nx">latitude</span> <span class="o">-</span> <span class="c1">//纬度.
</span><span class="c1"></span>                <span class="nx">longitude</span> <span class="o">-</span> <span class="c1">//经度. 
</span><span class="c1"></span>                <span class="nx">altitude</span> <span class="o">-</span> <span class="c1">//高度.
</span><span class="c1"></span>                <span class="nx">accuracy</span> <span class="o">-</span> <span class="c1">//精确度. 
</span><span class="c1"></span>                <span class="nx">altitudeAccuracy</span> <span class="o">-</span> <span class="c1">//高度的准确性. 
</span><span class="c1"></span>                <span class="nx">heading</span> <span class="o">-</span> <span class="c1">//. 
</span><span class="c1"></span>                <span class="nx">speed</span> <span class="o">-</span> <span class="c1">//.
</span><span class="c1"></span>            <span class="p">}</span>
            <span class="nx">timestamp</span> <span class="o">-</span> <span class="c1">//时间戳.
</span><span class="c1"></span>        <span class="p">}</span>

    <span class="p">},</span>

    <span class="c1">// 位置获取失败
</span><span class="c1"></span>    <span class="kd">function</span><span class="p">(</span><span class="nx">error</span><span class="p">){</span>

    <span class="p">}</span>
<span class="p">);</span>
</code></pre></div><p>如上，使用geolocation api很简单，只需要正确调用方法，等待返回坐标即可。</p>
<p>用户权限
由于geolocation api会暴露用户信息，所以当应用程序访问的时候，将以弹窗请求用户操作，如下</p>
<p>主机安全
另一个保护措施是使用HTTPS连接。由于一个新的网络安全策略，谷歌浏览器（桌面版和手机版）不再允许非安全的主机上运行的geolocation api。使用https可以最大限度的减少数据信息的盗用或被滥用的风险。</p>
<p>这里查看更多关于这个问题。</p>
<div class="highlight"><pre class="chroma"><code class="language-javascript" data-lang="javascript"><span class="nx">一个简单的Demo</span>
<span class="nx">findMeButton</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s2">&#34;click&#34;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(){</span>

    <span class="nx">navigator</span><span class="p">.</span><span class="nx">geolocation</span><span class="p">.</span><span class="nx">getCurrentPosition</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">position</span><span class="p">)</span> <span class="p">{</span>

        <span class="c1">// Get the coordinates of the current position.
</span><span class="c1"></span>        <span class="kd">var</span> <span class="nx">lat</span> <span class="o">=</span> <span class="nx">position</span><span class="p">.</span><span class="nx">coords</span><span class="p">.</span><span class="nx">latitude</span><span class="p">;</span>
        <span class="kd">var</span> <span class="nx">lng</span> <span class="o">=</span> <span class="nx">position</span><span class="p">.</span><span class="nx">coords</span><span class="p">.</span><span class="nx">longitude</span><span class="p">;</span>

        <span class="c1">// Create a new map and place a marker at the device location.
</span><span class="c1"></span>        <span class="kd">var</span> <span class="nx">map</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">GMaps</span><span class="p">({</span>
            <span class="nx">el</span><span class="o">:</span> <span class="s2">&#34;#map&#34;</span><span class="p">,</span>
            <span class="nx">lat</span><span class="o">:</span> <span class="nx">lat</span><span class="p">,</span>
            <span class="nx">lng</span><span class="o">:</span> <span class="nx">lng</span>
        <span class="p">});</span>

        <span class="nx">map</span><span class="p">.</span><span class="nx">addMarker</span><span class="p">({</span>
            <span class="nx">lat</span><span class="o">:</span> <span class="nx">lat</span><span class="p">,</span>
            <span class="nx">lng</span><span class="o">:</span> <span class="nx">lng</span>
        <span class="p">});</span>

    <span class="p">});</span>

<span class="p">});</span>
</code></pre></div><p><a href="https://jsfiddle.net/dannymarkov/ubrvm4ao/" title="https://jsfiddle.net/dannymarkov/ubrvm4ao/">在线demo</a></p>
<p>翻译自<a href="http://tutorialzine.com/2016/06/quick-tip-detecting-your-location-with-javascript/" title="http://tutorialzine.com/2016/06/quick-tip-detecting-your-location-with-javascript/">Detecting Your Location With JavaScript</a></p>

</div>

        <footer class="post-footer clearfix">
    
        <p class="post-tags">
            <span>Tagged:</span>
            
            
                <a href="/tags/translate/">translate</a>
            
        </p>
    

    <div class="share">
        
            <a class="icon-twitter" href="https://twitter.com/share?text=%e4%bd%bf%e7%94%a8js%e8%8e%b7%e5%8f%96%e4%bd%8d%e7%bd%ae&url=https%3a%2f%2fblog.steps.info%2f2020%2f01%2f19%2f%25E4%25BD%25BF%25E7%2594%25A8js%25E8%258E%25B7%25E5%258F%2596%25E4%25BD%258D%25E7%25BD%25AE%2f"
                onclick="window.open(this.href, 'twitter-share', 'width=550,height=235');return false;">
                <i class="fa fa-twitter"></i>
                <span class="hidden">Twitter</span>
            </a>
        

        
            <a class="icon-facebook" href="https://www.facebook.com/sharer/sharer.php?u=https%3a%2f%2fblog.steps.info%2f2020%2f01%2f19%2f%25E4%25BD%25BF%25E7%2594%25A8js%25E8%258E%25B7%25E5%258F%2596%25E4%25BD%258D%25E7%25BD%25AE%2f"
                onclick="window.open(this.href, 'facebook-share','width=580,height=296');return false;">
                <i class="fa fa-facebook"></i>
                <span class="hidden">Facebook</span>
            </a>
        

        
            <a class="icon-google-plus" href="https://plus.google.com/share?url=https%3a%2f%2fblog.steps.info%2f2020%2f01%2f19%2f%25E4%25BD%25BF%25E7%2594%25A8js%25E8%258E%25B7%25E5%258F%2596%25E4%25BD%258D%25E7%25BD%25AE%2f"
              onclick="window.open(this.href, 'google-plus-share', 'width=490,height=530');return false;">
              <i class="fa fa-google-plus"></i>
                <span class="hidden">Google+</span>
            </a>
        
        
    </div>
</footer>

        
    <div class="comments">
        
    </div>

    </article>
</div>

            </div>
        </div>

        <footer class="footer">
            <div class="container">
                <div class="site-title-wrapper">
                    <h1 class="site-title">
                        <a title="Homepage" href="https://blog.steps.info/">Homepage</a>
                    </h1>
                    <a class="button-square button-jump-top js-jump-top" href="#">
                        <i class="fa fa-angle-up"></i>
                    </a>
                </div>

                <p class="footer-copyright">
                    <span>&copy; 2020 / Powered by <a href="https://gohugo.io/">Hugo</a></span>
                </p>
                <p class="footer-copyright">
                    <span><a href="https://github.com/roryg/ghostwriter">Ghostwriter theme</a> By <a href="http://jollygoodthemes.com">JollyGoodThemes</a></span>
                    <span>/ <a href="https://github.com/jbub/ghostwriter">Ported</a> to Hugo By <a href="https://github.com/jbub">jbub</a></span>
                </p>
            </div>
        </footer>

        <script src="https://blog.steps.info/js/jquery-1.11.3.min.js"></script>
        <script src="https://blog.steps.info/js/jquery.fitvids.js"></script>
        <script src="https://blog.steps.info/js/scripts.js"></script>
    </body>
</html>

